#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "file_op.h"
#include "fs.h"
#include "disk.h"

#define MAX_CMD_LEN 256
#define MAX_ARG_NUM 4

void print_help() {
    printf("支持的命令:\n");
    printf("  mkdir /path\n");
    printf("  rmdir /path\n");
    printf("  rm /path\n");
    printf("  open /file\n");
    printf("  write /file content\n");
    printf("  cat /file\n");
    printf("  stat /file\n");
    printf("  rename /old /new\n");
    printf("  ls /dir\n");
    printf("  help\n");
    printf("  exit\n");
}

int disk_exists() {
    struct stat st;
    return stat("disk.img", &st) == 0;
}

int main() {
    disk_init();
    // 只格式化一次（如果 disk.img 文件还不存在）
    if (!disk_exists()) {
        fs_format();
    }
    fs_mount();

    char cmdline[MAX_CMD_LEN];
    char *argv[MAX_ARG_NUM];

    print_help();

    while (1) {
        printf(">> ");
        if (!fgets(cmdline, sizeof(cmdline), stdin)) break;

        // 去除换行
        cmdline[strcspn(cmdline, "\n")] = 0;

        // 拆分命令行
        int argc = 0;
        char *token = strtok(cmdline, " ");
        while (token && argc < MAX_ARG_NUM) {
            argv[argc++] = token;
            token = strtok(NULL, " ");
        }

        if (argc == 0) continue;

        // 命令解析
        if (strcmp(argv[0], "exit") == 0) {
            break;

        } else if (strcmp(argv[0], "mkdir") == 0 && argc == 2) {
            my_mkdir(argv[1]);

        } else if (strcmp(argv[0], "rmdir") == 0 && argc == 2) {
            my_rmdir(argv[1]);

        } else if (strcmp(argv[0], "rm") == 0 && argc == 2) {
            my_rm(argv[1]);

        } else if (strcmp(argv[0], "open") == 0 && argc == 2) {
            my_create(argv[1]);

        } else if (strcmp(argv[0], "write") == 0 && argc == 3) {
            my_write(argv[1], argv[2], strlen(argv[2]) + 1);

        } else if (strcmp(argv[0], "cat") == 0 && argc == 2) {
            char buf[1024];
            int n = my_read(argv[1], buf, sizeof(buf) - 1);
            if (n >= 0) {
                buf[n] = '\0';
                printf("%s\n", buf);
            }

        } else if (strcmp(argv[0], "stat") == 0 && argc == 2) {
            my_stat(argv[1]);

        } else if (strcmp(argv[0], "rename") == 0 && argc == 3) {
            my_rename(argv[1], argv[2]);

        } else if (strcmp(argv[0], "ls") == 0 && argc == 2) {
            my_ls(argv[1]);

        } else if (strcmp(argv[0], "help") == 0) {
            print_help();

        } else {
            printf("未知命令，输入 help 查看用法\n");
        }
    }

    disk_close();
    return 0;
}
